package com.ilop.sthome.ui.activity.scene;

import android.content.Intent;
import androidx.recyclerview.widget.GridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.example.common.base.BaseBindActivity;
import com.example.common.utils.LiveDataBus;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.data.greenDao.AutomationBean;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.ui.adapter.device.WeekAdapter;
import com.ilop.sthome.utils.CoderUtils;
import com.ilop.sthome.utils.tools.ByteUtil;
import com.example.common.view.WheelView;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivitySetTimingBinding;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author skygge
 * @date 2020-02-04.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：设置定时输入动作（触发条件）
 */
public class SettingTimingActivity extends BaseBindActivity<ActivitySetTimingBinding> {

    private boolean isAdd;
    private boolean isUpdate;
    private DeviceInfoBean mDevice;

    private WeekAdapter mAdapter;
    private ArrayList<String> items_hour;
    private ArrayList<String> items_min;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_set_timing;
    }

    @Override
    protected void initialize() {
        super.initialize();
        isAdd = getIntent().getBooleanExtra(CommonId.KEY_ADD_NEW, false);
        isUpdate = getIntent().getBooleanExtra(CommonId.KEY_UPDATE, false);
        mDevice = (DeviceInfoBean) getIntent().getSerializableExtra(CommonId.KEY_DEVICE);
    }

    @Override
    protected void initView() {
        super.initView();
        String timer_dw = "(" + getString(R.string.hour_and_min) + ")";
        mDBind.setTimeDw.setText(timer_dw);
        items_hour = new ArrayList<>();
        items_min = new ArrayList<>();
        mDBind.timerMinute.setCyclic(true);
        mDBind.timerHour.setCyclic(true);
        byte mWeekInt = 0x00;
        mAdapter = new WeekAdapter(mContext, mWeekInt);
        mDBind.weekTrigger.setLayoutManager(new GridLayoutManager(mContext, 4));
        mDBind.weekTrigger.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
        super.initData();
        for (int i = 0; i < 24; i ++) {
            String item = String.valueOf(i);
            if (item.length() == 1) {
                item = "0" + item;
            }
            items_hour.add(item);
        }

        for (int i = 0; i < 60; i ++) {
            String item = String.valueOf(i);
            if (item.length() == 1) {
                item = "0" + item;
            }
            items_min.add(item);
        }
        mDBind.timerHour.setAdapter(new NumberAdapter(items_hour));
        mDBind.timerMinute.setAdapter(new NumberAdapter(items_min));
        if (isUpdate){
            mDBind.btDelete.setVisibility(View.VISIBLE);
            String timer = mDevice.getDevice_status();
            String init_week = timer.substring(2, 4);
            int hour = Integer.parseInt(timer.substring(4, 6), 16);
            int min = Integer.parseInt(timer.substring(6), 16);
            mDBind.timerHour.setCurrentItem(hour);
            mDBind.timerMinute.setCurrentItem(min);
            byte ds = ByteUtil.hexStr2Bytes(init_week)[0];
            byte f;
            HashMap<Integer, Boolean> isSelected = new HashMap<>();
            for(int i=0;i<7;i++){
                f =   (byte)((0x02 << i) & ds);
                isSelected.put(i, f!=0);
            }
            mAdapter.setIsSelected(isSelected);
        }
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.ivBack.setOnClickListener(v -> finish());
        mDBind.tvSaveTiming.setOnClickListener(v -> {
            String setting_status = getTimerStringFromContent(mAdapter.getIsSelected(), mDBind.timerHour.getCurrentItem(), mDBind.timerMinute.getCurrentItem());
            Log.i(TAG, "initListener: "+setting_status);
            if(TextUtils.isEmpty(setting_status)){
                showToast(getString(R.string.set_first));
                return;
            }else{
                if(setting_status.startsWith("0300")){
                    showToast(getString(R.string.set_weekday));
                    return;
                }
                mDevice.setDevice_type("TIMER");
                mDevice.setDevice_status(setting_status);
            }
            if (isAdd){
                AutomationBean mAuto = new AutomationBean();
                List<DeviceInfoBean> mDeviceList = new ArrayList<>();
                mDeviceList.add(mDevice);
                mAuto.setDeviceName(mDevice.getDeviceName());
                mAuto.setInputList(mDeviceList);
                Intent intent = new Intent();
                intent.setClass(mContext, ChooseActionActivity.class);
                intent.putExtra(CommonId.KEY_ADD_SCENE, true);
                intent.putExtra(CommonId.KEY_INPUT, false);
                intent.putExtra(CommonId.KEY_DEVICE_NAME, mDevice.getDeviceName());
                intent.putExtra(CommonId.KEY_AUTOMATION, mAuto);
                startActivity(intent);
            }else {
                if (!isUpdate) {
                    LiveDataBus.get().with(CommonId.INPUT_CONDITION).setValue(mDevice);
                } else {
                    LiveDataBus.get().with(CommonId.INPUT_UPDATE).setValue(mDevice);
                }
            }
            finish();
        });
        mDBind.btDelete.setOnClickListener(view -> {
            LiveDataBus.get().with(CommonId.DELETE_CONDITION).setValue(true);
            finish();
        });
    }

    private String getTimerStringFromContent(HashMap<Integer, Boolean> week, int hour, int min) {
        byte f = 0x00;
        for(int i=0;i< week.size();i++){
            if(week.get(i)){
                f = (byte)((0x02 << i) | f);
            }
        }
        String weekDay = ByteUtil.convertByte2HexString(f);
        String hourDay = CoderUtils.setCodeSupplement1Byte(Integer.toHexString(hour));
        String minuteDay = CoderUtils.setCodeSupplement1Byte(Integer.toHexString(min));
        return "03" + weekDay + hourDay + minuteDay;
    }

    private class NumberAdapter extends WheelView.WheelArrayAdapter<String> {
        NumberAdapter(ArrayList<String> items) {
            super(items);
        }
    }
}
